package com.slipper.http;

import java.io.IOException;

import com.slipper.util.Tool;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.util.ContentCachingResponseWrapper;

public class HttpResponseWrapper extends ContentCachingResponseWrapper {
    public HttpResponseWrapper(HttpServletResponse httpServletResponse) {
        super(httpServletResponse);
    }

    public String getContent() throws IOException {
        if (isText(getContentType())) {
            byte[] content = super.getContentAsByteArray();
            try {
                return new String(content, super.getCharacterEncoding());
            } catch (Exception e) {
                return new String(content);
            } finally {
                copyBodyToResponse();
            }
        } else {
            return "[文件下载]";
        }
    }

    private boolean isText(String contentType) {
        return !Tool.isBlank(contentType)
                && (contentType.contains("application/json")
                    || contentType.contains("text/plain"));
    }
}
